package com.mrs.common.handle.security;

import com.alibaba.fastjson.JSON;
import com.mrs.common.ResponseResult;
import com.mrs.common.enums.AppHttpCodeEnum;
import com.mrs.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description: AuthenticationEntryPointImpl认证失败处理器
 * date: 2022/8/8 17:42
 * author: MR.孙
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //打印异常信息捕获异常类型方便,响应给前端
        e.printStackTrace();
        //BadCredentialsException :当用户名或者密码错误抛出此异常
        //InsufficientAuthenticationException :权限不足或需要登录时抛出此异常
        ResponseResult result=null;
        if(e instanceof BadCredentialsException){
            //这里返回的消息是异常类型的消息
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());
        }else if(e instanceof InsufficientAuthenticationException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else{
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),
                    "认证或者授权失败");

        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));

    }
}
